import { createStore } from "vuex";

const state = {
  // 消息提示文字
  msgText: "",
  // 消息提示类型：ok、error
  msgSuccess: false,
  //
  isRouter: false,
};

import getters from "./getters";
// 参数：1. 你要引入文件的目录 2.是否要查找该目录下的子级目录 3.匹配要引入的文件
const modulesFiles = require.context("./modules", true, /\.js$/);

// 不需要 import app from './modules/app'
// 它将自动 require 模块文件中的所有Vuex模块
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
  const value = modulesFiles(modulePath);
  modules[moduleName] = value.default;
  return modules;
}, {});

export default createStore({
  state: {
    ...state,
  },
  mutations: {
    commitSave(state, { key, data, local = false }) {
      if (!key) throw new Error("need key");
      const keyPath = key.split(".");
      let needSave = state;
      for (let i = 0; i < keyPath.length - 1; i++) {
        needSave = needSave[keyPath[i]];
        if (!needSave) {
          throw new Error(`error key: ${keyPath[i]}`);
        }
      }
      needSave[keyPath[keyPath.length - 1]] = data;
      if (local) {
        window.sessionStorage.setItem(key, JSON.stringify(data));
      }
    },
  },
  actions: {},
  getters,
  modules,
});
